<?php
/**
 * ロガー
 *
 * @author tanaka
 * @package File
 * @subpackage Logger
 */
class File_Logger
{
	const TYPE_APP_EXCEPTION = 'app_exception';
	const TYPE_BATCH = 'batch';

	/**
	 * インスタンス
	 * @var array
	 */
	protected static $_instance = array();

	/**
	 * ロガーの生成
	 *
	 * @param string $type self::TYPE_
	 * @return File_Logger
	 */
	public static function getInstance($type)
	{
		if (!isset(self::$_instance[$type])) {
			self::$_instance[$type] = new self($type);
		}

		return self::$_instance[$type];
	}

	/**
	 * ログレベル
	 * @var int
	 */
	protected $_level;

	/**
	 *
	 * @var Zend_Log
	 */
	protected $_writer;

	/**
	 * コンストラクタ
	 *
	 * @param string $type self::TYPE_
	 * @return void
	 */
	protected function __construct($type)
	{
		$config = App::getInstance()->getConfig()->log;

		if (!isset($config->$type)) {
			throw new AppException('設定項目が存在しない');
		}

		$filename = $config->$type->filename;

		if(isset($config->$type->addtime) && $config->$type->addtime){
			$replace = '_' . date('ymd') . '.';
			$filename = str_replace('.' , $replace, $filename);
		}

		$filename = $config->directory . '/' . $filename;

		$stream = new Zend_Log_Writer_Stream($filename);
		$this->_writer = new Zend_Log($stream);

		if(isset($config->$type->isErase) && $config->$type->isErase){
			if(file_exists($filename) && is_writable($filename)){
				file_put_contents($filename, "");
			}
		}

		if(!isset($config->$type->level)){
			$this->_level = Zend_Log::WARN;
			return;
		}

		$this->_level = $config->$type->level;
	}

	/**
	 * 書き込みを行います。
	 *
	 * @param string $message
	 * @return void
	 */
	public function write($message)
	{
		$this->_writer->log($message, $this->_level);
	}
}
